package 数据结构.队列.数组队列.循环队列;

import 数据结构.队列.Queue;

/**
 * @author Veng Su 1344114844@qq.com
 * @date 2018/7/17 14:56
 */
public class LoopQueue<E>  implements Queue<E> {
    private E[] data;
    private int front,tail;
    private int size;
    private LoopQueue(int capacity){
        data=(E[]) new Object[capacity+1];
        front=0;
        tail=0;
        size=0;
    }
    LoopQueue(){
        this(10);
    }

    private int getCapacity(){
        return data.length-1;
    }


    @Override
    public void enQueue(E e) {
        if ((tail+1)%data.length==front){
            resize((int) (getCapacity()*1.5));
        }
        data[tail]=e;
        tail=(tail+1)%data.length;
        size++;
    }

    private void resize(int capacity) {
        E[] newData= (E[]) new Object[capacity];
        for (int i = 0; i < size; i++) {
            newData[i]=data[(front+i)%data.length];
        }
        data=newData;
        front=0;
        tail=size;
    }

    @Override
    public E deQueue() {
        if (isEmpty()){
            throw new IllegalArgumentException("不能从空队列出队");
        }
        E ret=data[front];
        data[front]=null;
        front=(front+1)%data.length;
        size--;
        if (size==getCapacity()/4&&getCapacity()/2!=0){
            resize(getCapacity()/2);
        }
        return ret;
    }

    @Override
    public E getFront() {
        if (isEmpty()){
            throw  new IllegalArgumentException("队列为空");
        }
        return data[front];
    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return front==tail;
    }
    @Override
    public String toString() {
        StringBuilder stringBuilder=new StringBuilder();
        stringBuilder.append("ArrayQueue: front[");
        for (int i = front; i !=tail; i=(i+1)%data.length) {
            stringBuilder.append(data[i]);
            if ((i+1)%data.length!=tail){
                stringBuilder.append(",");
            }
        }
        stringBuilder.append("] tail");
        return stringBuilder.toString();
    }
}
